{% extends '_base.html' %}

{% block layout %}
	{% set __sidebar_left__ = true %}
{% endblock %}

{% block nav %} /user/ {% endblock %}

{% block title %}{{ _('Sponsor') }}{% endblock %}

{% block head %}

<style>
.x-discuss-visible {
    display: block;
}
</style>

<script>

var
    activeId = parseInt('{{ id }}'),
    TODAY = '{{ today }}',
    adSlots = JSON.parse(decodeURIComponent('{{ adSlots|json|url|raw }}')),
    adPeriods = JSON.parse(decodeURIComponent('{{ adPeriods|json|url|raw }}')),
    currentAdSlot = null,
    currentAdPeriod = null;

function getAdSlot(id) {
	return adSlots.find(function (s) {
		return s.id === id;
	});
}

function getAdPeriod(id) {
	return adPeriods.find(function (s) {
		return s.id === id;
	});
}

function getStatus(startAt, endAt) {
	if (TODAY >= endAt) {
		return "<span class=\"uk-text-danger\"><i class=\"uk-icon-stop-circle-o\"></i> " + "{{ _('Expired') }}" + "</span>";
	}
	if (startAt > TODAY) {
		return "<span class=\"uk-text-warning\"><i class=\"uk-icon-pause-circle-o\"></i> " + "{{ _('Pending') }}" + "</span>";
	}
	return "<span class=\"uk-text-success\"><i class=\"uk-icon-play-circle-o\"></i> " + "{{ _('Active') }}" + "</span>";
}

// init ad:

if (activeId > 0) {
	currentAdPeriod = getAdPeriod(activeId);
	currentAdSlot = getAdSlot(currentAdPeriod.adSlotId);
}

$(function () {
    $('#' + activeId).addClass('uk-active');
    if (activeId > 0) {
    	$('span.x-slot-name').text(currentAdSlot.name);
    	$('span.x-slot-description').text(currentAdSlot.description);
    	$('span.x-slot-size').text(currentAdSlot.width + ' x ' + currentAdSlot.height);
    	$('span.x-period-start').text(moment(currentAdPeriod.startAt).format('L'));
    	$('span.x-period-end').text(moment(currentAdPeriod.endAt).format('L') + ' ({{ _('Exclusive') }})');
    	$('span.x-period-status').attr('data-start', currentAdPeriod.startAt);
    	$('span.x-period-status').attr('data-end', currentAdPeriod.endAt);
    	$('span.x-status').each(function () {
    		var
    			$span = $(this),
    			start = $span.attr('data-start'),
    			end = $span.attr('data-end'),
    			status = getStatus(start, end);
    		$span.html(status);
    	});
    	
    	$('#image-preview').css('width', currentAdSlot.width + 'px');
    	$('#image-preview').css('height', currentAdSlot.height + 'px');
    }
});

$(function () {
	$('span.x-slot-info').each(function () {
		var
			$span = $(this),
			slot = getAdSlot(parseInt($span.attr('data-id')));
		$span.text(slot.name + ' (' + slot.width + ' x ' + slot.height + ')');
	});
});

function showMaterialForm() {
    $('#x-add-material').hide();
    $('#x-material-form').show();
}

function _showLarge(url) {
    var lightbox = UIkit.lightbox.create([{
        source: url,
        type: 'image'
    }]);
    lightbox.show();
}

function deleteAdMaterial(admId) {
    UIkit.modal.confirm('Are you sure you want to delete it?', function() {
        postJSON('/api/adMaterials/' + admId + '/delete', {}, function (err) {
            if (err) {
                _alert(err.message || err);
            } else {
                refresh();
            }
        });
    });
}

var imageData = null;

function _alert(msg) {
    UIkit.modal.alert(msg);
}

function _processImageFile(file, callback) {
    if (file.type!=='image/jpeg') {
        return _alert('Uploaded image must be JPEG format!');
    }
    var reader = new FileReader();
    reader.onload = function(e) {
        var
        	IMAGE_MAX_SIZE = currentAdSlot.width * currentAdSlot.height / 2,
        	IMAGE_MAX_SIZE_KB = Math.floor(IMAGE_MAX_SIZE / 1024),
            data = e.target.result;
            index = data.indexOf(';base64,');
        if ((index >= 0) && (index < 100)) {
            var theData = data.substring(index + 8);
            if (theData.length * 0.75 > IMAGE_MAX_SIZE) {
                return _alert('Image file is exceeded for ' + IMAGE_MAX_SIZE_KB + ' kb.');
            }
            var theImage = new Image();
            theImage.onload = function () {
                var
                    w = this.width,
                    h = this.height;
                if (w !== currentAdSlot.width || h !== currentAdSlot.height) {
                    return _alert('Image size is NOT exactly ' + currentAdSlot.width + ' x ' + currentAdSlot.height);
                }
                imageData = theData;
                callback({
                    image: data,
                    data: theData
                });
            };
            theImage.onerror = function () {
                return _alert('Not a valid image file!');
            };
            theImage.src = data;
        } else {
            return _alert('Browser does not support data URL!');
        }
    };
    reader.readAsDataURL(file);
}

$(function () {
    var
        $preview = $('#image-preview'),
        $form = $('#x-material-form'),
        $file = $form.find('input[name=file]'),
        $url = $form.find('input[name=url]'),
        $startAt = $form.find('input[name=startAt]'),
        $endAt = $form.find('input[name=endAt]'),
        $tags = $form.find('input[name=tags]'),
        $weight = $form.find('input[name=weight]');

    // watch file change:
    $('#file').change(function (evt) {
        evt.preventDefault();
        // clear:
        imageData = null;
        $preview.css('background-image', 'none');
        var f = $('#file').val();
        if (f === '') {
            // user cancelled selected file:
            return;
        }
        try {
            var file = $('#file').get(0).files[0];
            _processImageFile(file, function (r) {
                imageData = r.data;
                $preview.css('background-image', 'url(' + r.image + ')');
            });
        }
        catch (e) {
            UIkit.modal.alert('Error when process file: ' + e);
        }
    });

    $form.submit(function (e) {
        e.preventDefault();
        var data = {
            image: imageData,
            url: $url.val().trim(),
            startAt: $startAt.val(),
            endAt: $endAt.val(),
            tags: $tags.val().trim(),
            weight: parseInt($weight.val() || '100')
        };
        // check:
        if (data.image === null) {
            return _alert('Please select an image file.');
        }
        if (data.url === '' || (data.url.indexOf('http://') !== 0 && data.url.indexOf('https://') !== 0)) {
            return _alert('Invalid URL.');
        }
        if (data.startAt !== '' && data.endAt !== '' && data.startAt >= data.endAt) {
            return _alert('End date must be greater than start date.');
        }
        if (isNaN(data.weight) || data.weight <= 0 || data.weight > 100) {
            return _alert('Invalid weight.');
        }
        data.tags = _.filter(_.map(data.tags.split(','), function (s) {
            return s.trim();
        }), function (s) {
            return s !== '';
        }).join(',');

        $form.postJSON('/api/adPeriods/{{ id }}/adMaterials', data, function (err, r) {
            if (err) {
                return _alert('Create material failed: ' + (err.message || err.error));
            }
            location.assign('/sponsor/adperiod?id={{ id }}');
        });
    });
});
</script>
{% endblock %}

{% block sidebar_left_content %}
    <h3>{{ _('AD Subscriptions') }}</h3>
    <ul class="uk-nav uk-nav-side">
        <li class="uk-nav-header">Subscriptions</li>
    </ul>
    <ul class="uk-nav uk-nav-side" style="margin-right:-15px;">
        {% for p in adPeriods %}
        <li id="{{ p.id }}">
            <a href="/sponsor/adperiod?id={{ p.id }}"><i class="uk-icon-photo"></i> <span class="x-slot-info" data-id="{{ p.adSlotId }}"></span></a>
        </li>
        {% endfor %}
        <!--
        <li id="buyAdPeriod">
            <a href="/sponsor/buy"><i class="uk-icon-plus"></i> New Subscription</a>
        </li>
        -->
    </ul>
    <div class="x-placeholder"></div>
{% endblock %}

{% block content %}

	{% if id == 0 %}
    <div class="uk-alert uk-alert-warning">
        <p>No subscription yet.</p>
    </div>
    {% else %}

    <div class="x-ad-subscription uk-panel uk-panel-box">
        <h3 class="uk-panel-title">AD Subscription</h3>
        <hr>
        <p>AD name: <span class="x-slot-name"></span></p>
        <p>AD description: <span class="x-slot-description"></span></p>
        <p>AD size: <span class="x-slot-size"></span></p>
        <p>{{ _('Start at') }}: <span class="x-period-start"></span></p>
        <p>{{ _('End at') }}: <span class="x-period-end"></span></p>
        <p>{{ _('Status') }}: <span class="x-period-status x-status"></span></p>
    </div>

    <div class="x-placeholder"></div>

    <h3>AD Materials</h3>

    <table class="uk-table uk-table-hover">
        <thead>
            <tr>
                <th width="15%">{{ _('Image') }}</th>
                <th width="30%">{{ _('URL') }}</th>
                <th width="10%">{{ _('Start from') }}</th>
                <th width="10%">{{ _('End at') }} ({{ _('Exclusive') }})</th>
                <th width="10%">{{ _('Tags') }}</th>
                <th width="10%">{{ _('Weight') }}</th>
                <th width="10%">{{ _('Status') }}</th>
                <th width="5%">{{ _('Action') }}</th>
            </tr>
        </thead>
        <tbody>
            {% for m in adMaterials %}
            <tr>
                <td>
                    <a href="#0" onclick="_showLarge('/files/attachments/{{ m.imageId }}')"><img src="/files/attachments/{{ m.imageId }}/s"></a>
                </td>
                <td><a href="{{ m.url }}" target="_blank">{{ m.url }}</a></td>
                <td>{{ m.startAt.compareTo('1970-01-01') > 0 ? m.startAt : '' }}</td>
                <td>{{ m.endAt.compareTo('2100-01-01') < 0 ? m.endAt : '' }}</td>
                <td>{{ m.tags }}</td>
                <td>{{ m.weight }}</td>
                <td><span class="x-status" data-start="{{ m.startAt }}" data-end="{{ m.endAt }}"></span></td>
                <td>
                    <a href="javascript:deleteAdMaterial('{{ m.id }}')" title="Delete"><i class="uk-icon-trash"></i></a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

    <div id="x-add-material">
        <button class="uk-button uk-button-primary" onclick="showMaterialForm()" {% if adMaterials.length >= 10 %} disabled {% endif %} >Add Ad Material</button>
    </div>

    <div class="x-placeholder"></div>

    <form id="x-material-form" class="uk-form uk-form-stacked" style="display: none">
        <legend>{{ _('Add New AD Material') }}</legend>
        <fieldset>
            <div class="uk-alert uk-alert-danger uk-hidden"></div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('Image') }}: </label>
                <div class="uk-form-controls">
                    <div id="image-preview" style="border: 1px solid #ccc; background-size:cover;"></div>
                </div>
                <div class="uk-form-controls">
                    <input id="file" name="file" type="file">
                    <p>The uploaded image must be JPG format and exactly <span class="x-slot-size"></span>.</p>
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('URL') }}:</label>
                <div class="uk-form-controls">
                    <div class="uk-form-icon">
                        <i class="uk-icon-link"></i>
                        <input name="url" type="text" minlength="8" maxlength="1000" pattern="https?://.+" placeholder="https://example.com/landing.html" class="uk-form-width-large">
                    </div>
                    <p>The landing page URL. https is preferred.</p>
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('Start from') }}:</label>
                <div class="uk-form-controls">
                    <div class="uk-form-icon">
                        <i class="uk-icon-calendar"></i>
                        <input name="startAt" type="date" class="uk-form-width-medium">
                    </div>
                    <p>Optional: the AD will display from the specific date.</p>
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('End at') }} ({{ _('Exclusive') }}):</label>
                <div class="uk-form-controls">
                    <div class="uk-form-icon">
                        <i class="uk-icon-calendar"></i>
                        <input name="endAt" type="date" class="uk-form-width-medium">
                    </div>
                    <p>Optional: the AD will display only before the specific date.</p>
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('Keywords') }}:</label>
                <div class="uk-form-controls">
                    <div class="uk-form-icon">
                        <i class="uk-icon-tags"></i>
                        <input name="tags" type="text" placeholder="Tags seperated by ," class="uk-form-width-medium">
                    </div>
                    <p>Optional: the keywords of the AD. Seperated by ,</p>
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('Weight') }}: (1 ~ 100)</label>
                <div class="uk-form-controls">
                    <div class="uk-form-icon">
                        <i class="uk-icon-sliders"></i>
                        <input name="weight" type="number" value="100" min="1" max="100" placeholder="1 ~ 100" class="uk-form-width-medium">
                    </div>
                    <p>Optional: the weight of the AD: 1 ~ 100.</p>
                </div>
            </div>
            <!--
            <div class="uk-form-row">
                <label class="uk-form-label">GEO:</label>
                <div class="uk-form-controls">
                    <div class="uk-autocomplete uk-form-icon" data-uk-autocomplete="{source:'/api/geo'}">
                        <i class="uk-icon-map-marker"></i>
                        <input name="geo" type="text" class="uk-form-width-medium">
                    </div>
                    <p>Optional: the GEO of the AD.</p>
                </div>
            </div>
            -->
            <div class="uk-form-row">
                <div class="uk-form-controls">
                    <button type="submit" class="uk-button uk-button-primary"><i class="uk-icon-check"></i> {{ _('Save') }}</button>
                    &nbsp;
                    <button type="button" onclick="refresh()" class="uk-button x-cancel"><i class="uk-icon-times"></i> {{ _('Cancel') }}</button>
                </div>
            </div>
        </fieldset>
    </form>

    {% endif %}
{% endblock %}
